import { useState, useEffect, useRef } from "react";
import { Cat, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip";

const welcomeMessages = [
  "Hi there! I'm your AI study buddy, Meowrrror Agent 🐾",
  "I'm here to help you learn smarter, not harder!",
  "Need help setting goals or finding the right resource?",
  "You can click me anytime for tips or study reminders.",
  "Let's make today a productive one together!"
];

// 拖拽hook
function useDraggable(initialPosition = { x: window.innerWidth - 120, y: window.innerHeight - 180 }) {
  const [position, setPosition] = useState(initialPosition);
  const dragging = useRef(false);
  const offset = useRef({ x: 0, y: 0 });

  const onMouseDown = (e: React.MouseEvent) => {
    dragging.current = true;
    offset.current = {
      x: e.clientX - position.x,
      y: e.clientY - position.y,
    };
    document.addEventListener("mousemove", onMouseMove);
    document.addEventListener("mouseup", onMouseUp);
  };

  const onMouseMove = (e: MouseEvent) => {
    if (!dragging.current) return;
    setPosition({
      x: e.clientX - offset.current.x,
      y: e.clientY - offset.current.y,
    });
  };

  const onMouseUp = () => {
    dragging.current = false;
    document.removeEventListener("mousemove", onMouseMove);
    document.removeEventListener("mouseup", onMouseUp);
  };

  return { position, onMouseDown };
}

export const MirrorAgent = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [currentMessageIndex, setCurrentMessageIndex] = useState(0);
  const [displayedMessages, setDisplayedMessages] = useState<string[]>([]);
  const [isTyping, setIsTyping] = useState(false);
  const [messages, setMessages] = useState<{ role: 'user'|'ai', text: string }[]>([]);
  const [input, setInput] = useState("");
  const { position, onMouseDown } = useDraggable({ x: window.innerWidth - 120, y: window.innerHeight - 180 });

  const handleOpen = () => {
    setIsOpen(true);
    setCurrentMessageIndex(0);
    setDisplayedMessages([]);
    setIsTyping(true);
    
    // Start showing messages with delays
    setTimeout(() => {
      showNextMessage(0);
    }, 500);
  };

  const showNextMessage = (index: number) => {
    if (index < welcomeMessages.length) {
      setIsTyping(true);
      
      setTimeout(() => {
        setDisplayedMessages(prev => [...prev, welcomeMessages[index]]);
        setCurrentMessageIndex(index + 1);
        setIsTyping(false);
        
        // Show next message after a delay
        if (index + 1 < welcomeMessages.length) {
          setTimeout(() => {
            showNextMessage(index + 1);
          }, 1500);
        }
      }, 800);
    }
  };

  const handleClose = () => {
    setIsOpen(false);
    setDisplayedMessages([]);
    setCurrentMessageIndex(0);
    setIsTyping(false);
  };

  const handleSend = () => {
    if (!input.trim()) return;
    setMessages([...messages, { role: 'user', text: input }]);
    setTimeout(() => {
      setMessages(msgs => [...msgs, { role: 'ai', text: 'Mirror Agent 收到：' + input }]);
    }, 600);
    setInput("");
  };

  return (
    <div style={{ position: 'fixed', left: position.x, top: position.y, zIndex: 9999 }}>
      {isOpen && (
        <div className="mb-2 animate-scale-in">
          <Card className="w-80 shadow-lg border-2 border-orange-200 bg-gradient-to-br from-orange-50 to-pink-50">
            <CardHeader className="flex flex-row items-center justify-between pb-3 cursor-move" onMouseDown={onMouseDown} style={{ cursor: 'move' }}>
              <CardTitle className="text-lg font-semibold text-orange-700 flex items-center gap-2">
                <Cat className="h-5 w-5" />
                Mirror Agent
              </CardTitle>
              <Button
                variant="ghost"
                size="sm"
                onClick={handleClose}
                className="h-6 w-6 p-0 hover:bg-orange-100"
              >
                <X className="h-4 w-4" />
              </Button>
            </CardHeader>
            <CardContent className="pt-0 flex flex-col gap-2" style={{ maxHeight: 320, overflowY: 'auto' }}>
              {messages.length === 0 && <div className="text-gray-400 text-sm text-center py-8">How can I help you today?</div>}
              {messages.map((msg, idx) => (
                <div key={idx} className={msg.role === 'user' ? 'text-right' : 'text-left'}>
                  <span className={msg.role === 'user' ? 'inline-block bg-orange-100 text-orange-800 rounded-lg px-3 py-1 my-1' : 'inline-block bg-pink-100 text-pink-800 rounded-lg px-3 py-1 my-1'}>
                    {msg.text}
                  </span>
                </div>
              ))}
              <div className="flex gap-2 pt-2">
                <input
                  className="flex-1 border rounded px-2 py-1 text-sm focus:outline-none focus:ring-2 focus:ring-orange-200"
                  value={input}
                  onChange={e => setInput(e.target.value)}
                  onKeyDown={e => { if (e.key === 'Enter') handleSend(); }}
                  placeholder="Type a message..."
                />
                <Button size="icon" onClick={handleSend} disabled={!input.trim()}><Cat className="w-4 h-4" /></Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}
      {/* 浮动按钮 */}
      {!isOpen && (
        <TooltipProvider>
          <Tooltip>
            <TooltipTrigger asChild>
              <Button
                onClick={() => setIsOpen(true)}
                onMouseDown={onMouseDown} // 支持拖拽
                className="h-16 w-16 rounded-full bg-gradient-to-br from-orange-400 to-pink-400 hover:from-orange-500 hover:to-pink-500 shadow-lg hover:shadow-xl transition-all duration-300 group"
                size="icon"
                style={{ cursor: 'pointer' }}
              >
                <Cat className="h-8 w-8 text-white group-hover:scale-110 transition-transform duration-200" />
              </Button>
            </TooltipTrigger>
            <TooltipContent side="left" className="text-base font-medium">Mirror Agent</TooltipContent>
          </Tooltip>
        </TooltipProvider>
      )}
    </div>
  );
};
